package com.hpin.fansea.my;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.hpin.fansea.R;
import com.hpin.fansea.base.BaseActivity;
import com.hpin.fansea.bean.AuthResult;
import com.hpin.fansea.utils.CommonUtils;
import com.hpin.fansea.utils.Constant;
import com.hpin.fansea.utils.HttpUtil;
import com.hpin.fansea.widget.CircleImageView;
import com.lidroid.xutils.http.RequestParams;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.SimpleBitmapDisplayer;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 认证页面
 * Created by Aaron on 15/9/19.
 */
public class AuthActivity extends BaseActivity {

    private DisplayImageOptions options;
    private TextView tv_house_mun;
    private Button btn_done;
    private EditText et_real_name;
    private EditText tv_contact_tel;
    private EditText et_id_card;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_auth);

        options = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.mipmap.icon_headpic_default)
                .showImageForEmptyUri(R.mipmap.icon_headpic_default)
                .showImageOnFail(R.mipmap.icon_headpic_default)
                .resetViewBeforeLoading(true)
                .cacheOnDisk(true).cacheInMemory(true)
                .cacheOnDisc(true).imageScaleType(ImageScaleType.EXACTLY)
                .bitmapConfig(Bitmap.Config.RGB_565)
                .considerExifParams(true)
                .displayer(new SimpleBitmapDisplayer()).build();

        initWidget();

    }

    private void initWidget() {

        ImageView iv_left = (ImageView) findViewById(R.id.iv_left);
        TextView tv_title = (TextView) findViewById(R.id.tv_title);

        tv_title.setText(getResources().getString(R.string.my_auth));

        iv_left.setOnClickListener(this);

        setHeadInfo();

        TextView tv_city_name = (TextView) findViewById(R.id.tv_city_name);
        TextView tv_community_name = (TextView) findViewById(R.id.tv_community_name);
        LinearLayout ll_house_num = (LinearLayout) findViewById(R.id.ll_house_num);
        tv_house_mun = (TextView) findViewById(R.id.tv_house_mun);

        et_real_name = (EditText) findViewById(R.id.et_real_name);
        tv_contact_tel = (EditText) findViewById(R.id.tv_contact_tel);
        et_id_card = (EditText) findViewById(R.id.et_id_card);

        btn_done = (Button) findViewById(R.id.btn_done);

        tv_city_name.setText(sp.getString(Constant.cityName, ""));
        tv_community_name.setText(sp.getString(Constant.communityName, ""));

        et_real_name.setText(sp.getString(Constant.userName, ""));
        tv_contact_tel.setText(sp.getString(Constant.mobile, ""));
        et_id_card.setText(sp.getString(Constant.idNo, ""));

        ll_house_num.setOnClickListener(this);
        btn_done.setOnClickListener(this);

    }


    @Override
    protected void onResume() {
        super.onResume();

        //房号
        tv_house_mun.setText(
                CommonUtils.isNull(sp.getString(Constant.houseNo, "")) ?
                        "" :
                        sp.getString(Constant.communityId, "") + "期" + sp.getString(Constant.buildingNo, "") +
                                sp.getString(Constant.unitNo, "") + sp.getString(Constant.houseNo, ""));


        switch (sp.getString(Constant.status, "")) {

            case Constant.AUTH_USER:
            case Constant.AUTH_PASSED: //认证 和 认证通过用户

                btn_done.setBackgroundResource(getResources().getColor(R.color.gray));
                btn_done.setText("已认证");
                btn_done.setClickable(false);
                btn_done.setEnabled(false);
                btn_done.setFocusable(false);


                break;

            case Constant.AUTH_WAIT://待认证

                btn_done.setBackgroundResource(getResources().getColor(R.color.gray));
                btn_done.setText("认证中");
                btn_done.setClickable(false);
                btn_done.setEnabled(false);
                btn_done.setFocusable(false);

                break;

            case Constant.AUTH_RESUSED://认证不通过

                btn_done.setText("认证不通过");

                break;

        }

    }

    private void setHeadInfo() {

        // 头像
        CircleImageView head_img = (CircleImageView) findViewById(R.id.head_img);

        ImageLoader.getInstance().displayImage(sp.getString(Constant.headPic, ""), head_img, options);

        // 认证的图片
        ImageView my_auth = (ImageView) findViewById(R.id.my_auth);
        TextView tv_username = (TextView) findViewById(R.id.tv_username);
        TextView tv_community = (TextView) findViewById(R.id.tv_community);

        if (Constant.AUTH_USER.equals(sp.getString(Constant.status, "")) || Constant.AUTH_PASSED.equals(sp.getString(Constant.status, "")))
            my_auth.setVisibility(View.VISIBLE);
        else
            my_auth.setVisibility(View.INVISIBLE);

        tv_username.setText(sp.getString(Constant.nickname, ""));
        tv_community.setText(sp.getString(Constant.communityName, ""));

    }

    @Override
    public void widgetClick(View v) {

        switch (v.getId()) {

            case R.id.iv_left:

                finish();

                break;

            case R.id.btn_done://完成

                if (Constant.INTERFACE_USERTYPE_VISITOR.equals(sp.getString(Constant.status, ""))) {//游客
                    showToast("登录后才可以认证哦,亲~");
                    return;
                }

                if (CommonUtils.isNull(tv_house_mun.getText().toString().trim())) {
                    showToast("房号不能为空");
                    return;
                }
                if (CommonUtils.isNull(et_real_name.getText().toString().trim())) {
                    showToast("姓名不能为空");
                    return;
                }
                if (CommonUtils.isNull(tv_contact_tel.getText().toString().trim())) {
                    showToast("电话号码不能为空");
                    return;
                }
                if (!CommonUtils.isPhone(tv_contact_tel.getText().toString().trim())) {
                    showToast("手机号码格式不正确");
                    return;
                }
                if (CommonUtils.isNull(et_id_card.getText().toString().trim())) {
                    showToast("身份证号码不能为空");
                    return;
                }

                // 定义判别用户身份证号的正则表达式（要么是15位，要么是18位，最后一位可以为字母）
                Pattern idNumPattern = Pattern.compile("(\\d{14}[0-9a-zA-Z])|(\\d{17}[0-9a-zA-Z])");
                // 通过Pattern获得Matcher
                Matcher idNumMatcher = idNumPattern.matcher(et_id_card.getText().toString().trim());

                if (!idNumMatcher.matches()) {
                    showToast("身份证号码格式不正确!");
                    return;
                }

                //提交认证
                commit2Auth();

                break;

            case R.id.ll_house_num://房间号

                if (Constant.AUTH_USER.equals(sp.getString(Constant.status, ""))
                        || Constant.AUTH_PASSED.equals(sp.getString(Constant.status, ""))) {

                    showToast("您已经是认证用户了");
                    return;

                } else if (Constant.AUTH_WAIT.equals(sp.getString(Constant.status, ""))) {

                    showToast("正在认证中,请等待");
                    return;
                }

                //进入选择期次的页面
                Intent intent = new Intent(this, CommunityIssueActivity.class);
//                intent.putExtra("cityId", sp.getString(Constant.cityId, ""));
                intent.putExtra("communityId", sp.getString(Constant.communityId, ""));
                startActivity(intent);

                break;

            default:
                break;
        }
    }

    /**
     * 提交认证
     */
    private void commit2Auth() {

        RequestParams params = new RequestParams();
        params.addBodyParameter("lng", "");// 经度
        params.addBodyParameter("lat", "");// 维度
        params.addBodyParameter("userName", et_real_name.getText().toString().trim());
        params.addBodyParameter("userId", tv_contact_tel.getText().toString().trim());// 手机号
        params.addBodyParameter("communityId", sp.getString(Constant.communityId, ""));// 期次ID
        params.addBodyParameter("idCardNo", et_id_card.getText().toString().trim());
        params.addBodyParameter("buildingNo", sp.getString(Constant.buildingNo, ""));
        params.addBodyParameter("unitNo", sp.getString(Constant.unitNo, ""));
        params.addBodyParameter("houseNo", sp.getString(Constant.houseNo, ""));
        params.addBodyParameter("token", sp.getString(Constant.token, ""));
        params.addBodyParameter("systemType", Constant.SYSTEM_TYPE);
        HttpUtil.getInstance().setPostRequest("提交中...", this, Constant.WEB_ROOT + Constant.AUTH, params, new HttpUtil.SuccessListener() {
            @Override
            public void setOnSuccessListener(String str) {

                try {

                    AuthResult authResult = JSONObject.parseObject(str, AuthResult.class);

                    if (Constant.STATUS_SUCESS.equals(authResult.status)) {

                        switch (authResult.userStatus) {

                            case Constant.STATUS_VISITOR:
                                showToast("认证失败!");
                                break;

                            case Constant.REGISTER_USER:
                                showToast("认证中,请等待!");
                                break;

                            case Constant.AUTH_USER:
                            case Constant.AUTH_PASSED:

                                showToast("认证成功!");

                                btn_done.setBackgroundResource(getResources().getColor(R.color.gray));
                                btn_done.setText("已认证");
                                btn_done.setClickable(false);
                                btn_done.setEnabled(false);
                                btn_done.setFocusable(false);

                                break;

                            case Constant.AUTH_RESUSED:
                                showToast("认证未通过!");
                                break;

                            case Constant.AUTH_LOCK:
                            case Constant.AUTH_OUT:
                                showToast("账号存在异常!");
                                break;

                            case Constant.AUTH_WAIT:
                                showToast("请等待认证!");
                                break;

                        }

                    } else {
                        showToast(authResult.message);
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                    showToast("提交失败");
                }

            }
        }, null);

    }
}